//
//  CRTopicPictureView.m
//  CRChatRoom
//
//  Created by CuiFengshuai on 15/11/28.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRTopicPictureView.h"
#import "CRProgressView.h"
#import "CRTopic.h"
#import "UIImageView+WebCache.h"
@interface CRTopicPictureView ()
@property (weak, nonatomic) IBOutlet UIImageView *gifView;
@property (weak, nonatomic) IBOutlet UIButton *seeBigButton;
@property (weak, nonatomic) IBOutlet CRProgressView *progressView;

@end


@implementation CRTopicPictureView

// 重写 setter方法
- (void)setTopic:(CRTopic *)topic {
    [super setTopic:topic];
    // 覆盖下载进度
    self.progressView.progress = topic.pictureProgress;
    [_imageView sd_setImageWithURL:[NSURL URLWithString:topic.large_image] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
        // 显示进度条
        self.progressView.hidden = NO;
        // 计算进度
        self.progressView.progress = 1.0 * receivedSize / expectedSize;
        // 更新下载进度
        topic.pictureProgress = self.progressView.progress;
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        // 隐藏进度条
        self.progressView.hidden = YES;
        // 进度设置为1
        topic.pictureProgress = 1.0;
        
        if (topic.isBigPicture == NO) {
            return ;
        }
        
        // 将大图片 -> 小图片
        UIGraphicsBeginImageContext(_imageView.frame.size);
        
        [image drawInRect:CGRectMake(0, 0, _imageView.width, _imageView.width * topic.height / topic.width)];
        
        _imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
    }];
    
    self.gifView.hidden = !topic.is_gif;
    self.seeBigButton.hidden = !topic.isBigPicture;
}
@end
